package worker;

import Settings.ServerData;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import openInternetServer.OpenInternetServerImplementation;
import org.apache.log4j.Logger;

public class UDPMessageHandler extends Thread {

    protected DatagramSocket socket;
    protected DatagramPacket sendPacket;
    protected DatagramPacket receivePacket;
    protected byte data[];
    private boolean running;
    private Logger logger = Logger.getLogger(UDPMessageHandler.class);
    private int port;

    public UDPMessageHandler(int port_param) {
        port = port_param;
        try {
            socket = new DatagramSocket(port, InetAddress.getByName(OpenInternetServerImplementation.serverIPStr));
            logger.debug("UDP MessageHandler started on port " + port);
        } catch (Exception e) {
            logger.fatal("Exception at Starting UDP MessageHandler on Port: " + port, e);
        }
    }

    public void processData() {

        boolean sendServerFileContent = false;
        String serverFileContent = null;
        String result = "content_not_matched";
        String receivedStr = new String(data, 0, receivePacket.getLength());

        for (int i = 0; i < ServerData.testSettingsObjects.size(); i++) {
            if (ServerData.testSettingsObjects.get(i).fileContentClient != null) {
                if (receivedStr.equals(ServerData.testSettingsObjects.get(i).fileContentClient)) {
                    result = "content_matched";
                    sendServerFileContent = true;
                    serverFileContent = ServerData.testSettingsObjects.get(i).fileContentServer;
                    
                }
            }
        }
        //sending ACK
        try {
            send(result.getBytes(), result.getBytes().length, receivePacket.getAddress(), receivePacket.getPort());

        } catch (Exception ex) {
            logger.fatal("Exception while sending ACK in UDP MessageHandler", ex);
        }

        try{
            Thread.sleep(2000);
        }catch(Exception ex)
        {
            logger.fatal("interrupted: "+ex);
        }
        //sending serverFileContent (if content matched)
        if (sendServerFileContent&&serverFileContent!=null) {
            try {
                send(serverFileContent.getBytes(), serverFileContent.getBytes().length, receivePacket.getAddress(), receivePacket.getPort());

            } catch (Exception ex) {
                logger.fatal("Exception while sending Server File Content packet in UDP MessageHandler", ex);
            }
        }

    }

    @Override
    public void run() {
        running = true;

        data = new byte[4096];

        receivePacket = new DatagramPacket(data, data.length);

        while (running) {
            try {
                socket.receive(receivePacket);
                logger.debug("Got a new message from a client from: " + receivePacket.getAddress() + " on Port: " + port);
                processData();

            } catch (Exception ex) {

                logger.fatal("Exception in UDP Message Handler running on Port: " + port, ex);
                break;
            }
        }
    }

    public void send(byte data[], int length, java.net.InetAddress mediaNodeIP, int Port) throws Exception {

        sendPacket = new DatagramPacket(data, length);

        try {
            sendPacket.setAddress(mediaNodeIP);
            sendPacket.setPort(Port);
            sendPacket.setLength(length);
            socket.send(sendPacket);
        } catch (Exception ex) {
            logger.fatal("Exception in sending UDP message", ex);
        }
    }

    public void shutDown() {

        try {
            running = false;

            if (socket != null && !socket.isClosed()) {
                socket.close();
                logger.debug("UDP MessageHandler shut down successfully on Port: " + port);
            }
        } catch (Exception ex) {
            logger.fatal("Exception in shutting down UDPMessageHandler on Port: " + port, ex);
        }
    }
}
